package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.TimeZoneUtil;
import util.enviaEmail;
import bean.OSBean;
import bean.comissaoBean;
import bean.designerBean;
import conexao.Conexao;
import dao.OSDao;
import dao.comissaoDao;
import dao.designerDao;

public class enviaOsDesignerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public enviaOsDesignerServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		PrintWriter out = response.getWriter();
		
		Connection conn = null;
		try {
			conn = new Conexao().getConexao();
		} catch (SQLException e) {
			new enviaEmail().enviar(e);
			out.print("falhaConexao");
			return;
		}
		
		Integer idOS = Integer.parseInt(request.getParameter("idOS"));
		Integer idDesigner = Integer.parseInt(request.getParameter("idDesigner"));
				
		try {
		OSBean osBean = new OSBean();
		osBean.setId(idOS);
		osBean.setDataDesigner(new TimeZoneUtil().getHoraLocal());
		
		OSBean bean = new OSDao().getOsDesigner(conn, osBean);
		
		comissaoBean beanco = new comissaoBean();
		beanco.setIdOS(idOS);
		beanco.setIdFuncionario(idDesigner);
		
		designerBean desi = new designerBean();
		desi.setIddesigner(idDesigner);
		desi.setIdos(idOS);

			//se a os não pertencer a nenhum designer
			if(!new OSDao().isOSDesigner(conn, osBean)){
				new OSDao().enviaOSDesigner(conn, osBean);
				new comissaoDao().inserir(conn, beanco);
				new designerDao().inserir(conn, desi);
				
				conn.commit();
				out.print("atualiza");
				return;
			}else if(bean.getIdDesigner() != idDesigner){
				out.print("Esta OS foi designada para o designer " +bean.getNomeDesigner()+ ". Informe o motivo de estar mudando a OS de designer?");
				return;
			}
			out.print("naoAtualiza");

		} catch (Exception e) {
			try {
				conn.rollback();
			} catch (Exception ex) {
				new enviaEmail().enviar(ex);
				ex.printStackTrace();
			}
			new enviaEmail().enviar(e);
			throw new RuntimeException(e);
		} finally {
			try {
				conn.close();
			} catch (Exception ex) {
				new enviaEmail().enviar(ex);
			}
		}
		
	}

}
